/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package InfoMat;

import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.sensor.*;
import javax.microedition.io.Connector;
import javax.microedition.media.*;
import java.io.*;
import sUtils.*;


/**
 *
 * @author thomas.s
 */
public class InfoMat extends MIDlet implements CommandListener {
    InfoCanvas canvas;
    RSSMenu menu;
    Command exitCommand;
    Command loadCommand;
    Command menuCommand;

    public InfoMat() {
        Lang.init();
        exitCommand = new Command ( Lang.word("Quit","Beenden"), Command.EXIT, 1);
        loadCommand = new Command ("Online", Command.OK, 0);
        menuCommand = new Command ("Feeds", Command.BACK, 0);
        menu = new RSSMenu(this);
        menu.addCommand (exitCommand);
        menu.setCommandListener(this);

        canvas = new InfoCanvas(this);
        canvas.addCommand (menuCommand);
        canvas.addCommand (loadCommand);
        canvas.setCommandListener (this);
    }

    public void startApp() {
       showMenu();
    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {}

    public void close()
    {
        canvas = null;
        destroyApp(true);
        notifyDestroyed();
    }
    public void commandAction(Command c, Displayable s) {
        if (c == exitCommand) close(); else
        if (c == menuCommand) showMenu(); else
        if (c == loadCommand) canvas.load();
    }

    public void showFeed()
    {
       canvas.current=-1;
       canvas.sy=0; canvas.sx=0;
       canvas.rss.setURL( canvas.st, menu.url(), menu.name(), menu.utf8() );
       canvas.lastUpdate = 0;
       canvas.b_offline = true;
       canvas.b_valid = false;
       Display.getDisplay(this).setCurrent( canvas );
    }

    public void showMenu()
    {
        Display.getDisplay(this).setCurrent( menu );
    }

   class InfoCanvas extends Canvas implements DataListener {
       public InfoMat parent;
       public NewsStorage st = new NewsStorage();
       public RSSReader rss = new RSSReader();
       private Timer timer=new Timer();
       private Player player=null;
       SensorConnection sensor;
       boolean b_landscape=false;
       boolean b_loading=false;
       boolean b_offline=false;
       boolean b_valid=false;

       long lastUpdate=0,lastPressed=0;
       int sy=0,sx=0,mx,my,dx=0;
       int current=-1;

       public InfoCanvas( InfoMat p )
       {
            parent = p;
            SensorInfo[] sensors = SensorManager.findSensors(null,null);
            for ( int i=0; i<sensors.length; i++ )
            {
                if (sensors[i].getQuantity().equalsIgnoreCase("acceleration"))
                {
                    try {
                        sensor = (SensorConnection) Connector.open(sensors[i].getUrl());
                        sensor.setDataListener(this, 1);
                    } catch (IOException e) { }
                    break;
                }
            }
            player = Sounds.load(null, "/sonar.mp3", "audio/mpeg");
            timer.schedule(new updateTask(this), 0, 100);
       }

       public void response( boolean news )
       {
           if (news) {
               if (player!=null) try { player.start(); } catch(Exception e) {}
               Display.getDisplay(parent).flashBacklight(20);
               Display.getDisplay(parent).vibrate(400);
          }
       }

       public void load()
       {
           b_offline=false;
           lastUpdate=0;
       }

       public void refresh()
       {
           b_offline = true;
           b_loading = true;
       }

       class updateTask extends TimerTask {
            private InfoCanvas canvas;
            updateTask( InfoCanvas c ){  canvas = c;  }
            public void run() {
                canvas.update(); }
       }

       public void update()
       {
            if ( lastUpdate==0 || (parent.menu.auto() && !b_offline && ((System.currentTimeMillis()-lastUpdate)>60000)))
            {
                b_loading = true;
                //b_offline = false;
                lastUpdate = System.currentTimeMillis();
                repaint();
            }
            else
            if (b_loading)
            {
                rss.readRSS(st,b_offline);
                st.updateImage(0x202020,parent.menu.size());
                b_loading=false;
                b_valid=true;

                repaint();
                response(st.changed);
            }
       }

       public void paint(Graphics g) {
            int w = getWidth();
            int h = getHeight();

            g.setColor(0xb0b0b0);
            g.fillRect(0,0,800,800);
            g.setColor(0xe0e0f0);
            if (b_valid)
            {
            if (b_landscape)
            {
                if (st.screenL!=null)
                {
                    Image img = (Image)(st.screenL.elementAt(0));
                    int iw = img.getWidth(), ih = img.getHeight();
                    for ( int i=1; i<st.screenL.size(); i++)
                    {
                        if (current==i) g.fillRect(w-iw-i*iw-sy, 0, iw, ih);
                        g.drawImage((Image)(st.screenL.elementAt(i)), w-iw-i*iw-sy, 0, 0);
                    }
                    g.setColor(menu.auto()?0x800000:0x000080);
                    g.fillRect(w-iw,0,iw,h);
                    g.drawImage(img, w-iw, 0, 0);

                }
            }
            else
            {
                if (st.screenH!=null)
                {
                    Image img = (Image)(st.screenH.elementAt(0));
                    int iw = img.getWidth(), ih = img.getHeight();
                    
                    for ( int i=1; i<st.screenH.size(); i++)
                    {
                        if (current==i) g.fillRect(sx, i*ih+sy, iw, ih);
                        g.drawImage((Image)(st.screenH.elementAt(i)), sx, i*ih+sy, 0);
                    }

                    g.setColor(menu.auto()?0x800000:0x000080);
                    g.fillRect(0,0,w,ih);
                    g.drawImage(img, 0, 0, 0);

                }
            }
            }
            if (b_loading)
            {
                String s = Lang.word( b_offline ? "Load offline" : "Load online",
                        b_offline ? "Lade offline" : "Lade online" );
                int tw = g.getFont().stringWidth(s);
                int th = g.getFont().getBaselinePosition();
                g.setColor(0);
                g.drawString(s,(w-tw)/2+2,(h-th)/2+2,0);
                g.setColor(0xffffff);
                g.drawString(s,(w-tw)/2,(h-th)/2,0);
            }

        }

        public void dataReceived( SensorConnection conn, Data[] arg, boolean lost )
        {
            // daten von den Sensoren einlesen
            double y = Math.abs(arg[1].getDoubleValues()[0]);
            double z = Math.abs(arg[2].getDoubleValues()[0]);
            if (z<12) // aufrecht bitte!
            {
                if (!b_landscape && y<5) { b_landscape=true; repaint(); } else
                if (b_landscape && y>10) { b_landscape=false; repaint(); }
            }
        }

        public void pointerPressed( int x, int y )
        {
            mx=x; my=y; dx=0; lastPressed = System.currentTimeMillis();

            if (!b_landscape)
            {
                if (st.screenH!=null)
                {
                    Image img = (Image)(st.screenH.elementAt(0));
                    int iw = img.getWidth(), ih = img.getHeight();
                    current = (y-sy) / ih;
                    repaint();
                }
            }
            else
            {
                if (st.screenL!=null)
                {
                    Image img = (Image)(st.screenL.elementAt(0));
                    int iw = img.getWidth(), ih = img.getHeight(), w = getWidth();
                    current = (w-iw-sy-x) / iw;
                    repaint();
                }
            }

        }

        public void pointerReleased( int x, int y )
        {
            sx=0; repaint();
        }

        public void pointerDragged( int x, int y )
        {
            int oy = sy, ox = sx;
            Image img = (Image)(st.screenH.elementAt(0));
            int maxH = img.getHeight()*st.screenH.size();
            
            sy += (b_landscape?(mx-x):(y-my));
            dx += (!b_landscape?(x-mx):(my-y));
            if (dx>100) sx += (dx-100)/4; else if (dx<-100) sx += (dx+100)/4;
            mx=x; my=y;
            if (sy>0) sy=0; else
            if (sy<0)
            {
                int max = b_landscape?(getWidth()-maxH):(getHeight()-maxH);
                if (max>=0) sy=0; else if (sy<max) sy = max;
            }
            if (sx>0) sx=0;
            if (sy!=oy || sx!=ox) repaint();
        }
    } // InfoCanvas
}
